<?php
/**
 * 文件名：qqwb.mod.php
 * 版本号：1.0
 * 最后修改时间：2011年3月3日
 * 作者：狐狸<foxis@qq.com>
 * 功能描述: QQ微博接口模块
 */


if(!defined('IN_JISHIGOU'))
{
	exit('invalid request');
}

class ModuleObject extends MasterObject
{

	var $QQWBConfig = array();

	var $QQWBBindInfo = array();

	var $QQWBApi = array();

	var $UserInfo = array();


	function ModuleObject($config)
	{
		$this->MasterObject($config);

		$this->_init_qqwb();

		$this->Execute();
	}


	function Execute()
	{
	   require_once ROOT_PATH.'private/classes/qq.inc.php';
       $qqinc = new qqinc($this);
       	
		ob_start();
		switch ($this->Code)
		{
			case 'login':
				$this->Login();
				break;

			case 'auth_callback':
				$this->AuthCallback();
				break;

			case 'login_check':
				$this->LoginCheck();
				break;

			case 'do_login':
				$this->DoLogin();
				break;

			case 'reg_check':
				$this->RegCheck();
				break;

			case 'do_reg':
				$this->DoReg();
				break;

			case 'unbind':
				$this->UnBind();
				break;

			case 'do_modify_bind_info':
				$this->DoModifyBindInfo();
				break;
			case 'synctopic':
				$qqinc->SyncTopic();
				break;
			case 'syncreply':
				$qqinc->SyncReply();
				break;

			default:
				$this->Main();
		}
		$body=ob_get_clean();

		$this->ShowBody($body);
	}

	function Main()
	{
		$this->Messager("未定义的操作",null);

	}

	function Login()
	{
		$aurl = $this->_get_oauth_url();


		$this->Messager(null,$aurl);
	}

	function AuthCallback()
	{
		$qqwb_oauth_token_secret = $_SESSION['qqwb_oauth_token_secret'] ? $_SESSION['qqwb_oauth_token_secret'] : jsg_getcookie('qqwb_oauth_token_secret');
		if(!$qqwb_oauth_token_secret || !$_REQUEST['oauth_token'])
		{
			$this->Messager(null,'index.php');
		}

		require_once(ROOT_PATH . 'include/qqwb/qqoauth.php');

		$QQAuth = new QQOAuth($this->QQWBConfig['app_key'],$this->QQWBConfig['app_secret'],$_REQUEST['oauth_token'],$qqwb_oauth_token_secret);

		$last_keys = $QQAuth->getAccessToken($_REQUEST['oauth_verifier']);

		if(!$last_keys['oauth_token'] || !$last_keys['oauth_token_secret'])
		{
			$this->Messager(null,'index.php');
		}

		$QQAuth = new QQOAuth($this->QQWBConfig['app_key'],$this->QQWBConfig['app_secret'],$last_keys['oauth_token'],$last_keys['oauth_token_secret']);

		$QQInfo = $QQAuth->OAuthRequest('http:/'.'/open.t.qq.com/api/user/info?format=json', 'GET',array());

		unset($_SESSION['qqwb_oauth_token_secret']);
		jsg_setcookie('qqwb_oauth_token_secret','');

		if(!$QQInfo)
		{
			$this->Messager('连接失败',null);
		}
		if('no auth'==$QQInfo)
		{
			$this->Messager($QQInfo,null);
		}

		$QQInfo = json_decode($QQInfo);
		if(!$QQInfo || !$QQInfo->data)
		{
			$this->Messager('解析失败',null);
		}

		$QQInfo = $QQInfo->data;
		if(!$QQInfo->name)
		{
			$this->Messager('内容错误',null);
		}

		$qqwb_bind_info = $this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."qqwb_bind_info where `qqwb_username`='{$QQInfo->name}'");

		if($qqwb_bind_info)
		{
			if($last_keys['token']!=$last_keys['oauth_token'] || $last_keys['ksecret']!=$last_keys['oauth_token_secret'])
			{
				$this->DatabaseHandler->Query("update ".TABLE_PREFIX."qqwb_bind_info set `token`='{$last_keys['oauth_token']}',`tsecret`='{$last_keys['oauth_token_secret']}' where `qqwb_username`='{$QQInfo->name}'");
			}
			
			$this->Messager("该微博账号已经绑定了",'index.php');
		}
		else
		{
			if(MEMBER_ID > 0)
			{
				$this->DatabaseHandler->Query("insert into ".TABLE_PREFIX."qqwb_bind_info (`uid`,`qqwb_username`,`token`,`tsecret`,`dateline`,`synctoqq`) values ('".MEMBER_ID."','{$QQInfo->name}','{$last_keys['oauth_token']}','{$last_keys['oauth_token_secret']}','".time()."',1)");

				//同步财经的用户信息
				include_once ROOT_PATH."/caijing/CaijingUtil.php";
				$util = new CaijingUtil();
				$util->lockQwb($QQInfo->name);

				$this->Messager(null,'index.php?mod=tools&code=qqwb');
			}
			else
			{
				$qqwb_username = $QQInfo->name;
				$token = $last_keys['oauth_token'];
				$tsecret = $last_keys['oauth_token_secret'];

				$reg = array();
				$reg['username'] = $QQInfo->name;
				$reg['nickname'] = array_iconv('utf-8',$this->Config['charset'],$QQInfo->nick);
				if($this->QQWBConfig['is_sync_face'] && $QQInfo->head)
				{
					$reg['face'] = $QQInfo->head . '/180';
				}


				$this->Title = 'QQ微博帐号绑定';
				include($this->TemplateHandler->Template('qqwb_bind_info'));
			}
		}
	}

	function RegCheck()
	{
		exit($this->_reg_check());
	}
	function _reg_check()
	{
		$return = '';

		$in_ajax = $this->Request['in_ajax'];
		if($in_ajax)
		{
			$this->Post = array_iconv('utf-8',$this->Config['charset'],$this->Post);
		}

		$username = trim($this->Post['username']);
		$nickname = trim($this->Post['nickname']);
		$password = trim($this->Post['password']);
		$email = trim($this->Post['email']);
		if(!$username || !$nickname)
		{
			return '用户名或昵称不能为空';
		}
		if(!$password || !$email)
		{
			return '邮箱或密码不能为空';
		}
		if(!preg_match('~^[\w\d\_]{1,15}$~i',$username))
		{
			return '用户名只允许数字和字母';
		}
		$forbids = array('master'=>1,'topic'=>1,'index'=>1,'admin'=>1,'ajax'=>1,'login'=>1,'member'=>1,'profile'=>1,'tag'=>1,'get_password'=>1,'report'=>1,'weather'=>1,'imjiqiren'=>1,'sms'=>1,'qqwb'=>'1','url'=>1,'api'=>1,'backup'=>1,'cache'=>1,'data'=>1,'errorlog'=>1,'iis_rewrite'=>1,'images'=>1,'include'=>1,'install'=>1,'modules'=>1,'setting'=>1,'templates'=>1,'uc_client'=>1,'wap'=>1,);
		if(isset($forbids[$username]))
		{
			return '用户名被禁止使用';
		}
		if(isset($forbids[$nickname]))
		{
			return '昵称被禁止使用';
		}
		if(($filter_result = filter($username)))
		{
			return '用户名'.$filter_result;
		}
		if(($filter_result = filter($nickname)))
		{
			return '昵称'.$filter_result;
		}
		if (!preg_match("~^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$~i",$email))
		{
			return '邮箱地址错误';
		}
		if ($this->Config['reg_email_forbid'] && false!==stristr($this->Config['reg_email_forbid'],strstr($email,'@')))
		{
			return '邮箱地址禁止注册';
		}
		if (($this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `username`='$username'")) || ($this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `nickname`='$username'")))
		{
			return '用户名已经被注册';
		}
		if (!$this->Config['reg_email_doublee'] && $this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `email`='$email'"))
		{
			return '邮箱已经被注册';
		}
		if ($this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `username`='$nickname'") || $this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `nickname`='$nickname'"))
		{
			return '昵称已经被注册';
		}

		if(true===UCENTER)
		{
			include_once(ROOT_PATH . 'uc_client/client.php');

			$uc_result = uc_user_checkname($username);
			if($uc_result < 1)
			{
				$uc_results = array
				(
                    '-1'=>'用户名不合法',
                    '-2'=>'用户名不允许注册',
                    '-3'=>'用户名已经存在',
				);

				return $uc_results[$uc_result];
			}

			$uc_result = uc_user_checkemail($email);
			if($uc_result < 1)
			{
				$uc_results = array
				(
                    '-4'=>'Email 格式有误',
                    '-5'=>'Email 不允许注册',
                    '-6'=>'Email 已经被注册',
				);

				return $uc_results[$uc_result];
			}
		}

		return $return;
	}
	function DoReg()
	{
		if(($check_result = $this->_reg_check()))
		{
			$this->Messager($check_result,null);
		}

		$timestamp = time();

		$username = trim($this->Post['username']);
		$nickname = trim($this->Post['nickname']);
		$password = trim($this->Post['password']);
		$email = trim($this->Post['email']);

		$ucuid = 0;
		if(true===UCENTER)
		{
			include_once(ROOT_PATH . 'uc_client/client.php');

			$uc_result = uc_user_register($username,$password,$email);
			if($uc_result > 0)
			{
				$ucuid = $uc_result;
			}
		}

		$sql_datas = array();
		$sql_datas['ucuid'] 	= $ucuid;
		$sql_datas['password']	= md5($password);
		$sql_datas['username']	= mysql_escape_string($username);
		$sql_datas['nickname']  = ($nickname ? mysql_escape_string($nickname) : $sql_datas['username']);
		$sql_datas['email'] 	= mysql_escape_string($email);
		$sql_datas['role_type']	= 'normal';
		$sql_datas['role_id'] 	= (int) ($this->Config['reg_email_verify'] ? $this->Config['no_verify_email_role_id'] : $this->Config['normal_default_role_id']);
		$sql_datas['secques'] 	= '';
		$sql_datas['invitecode']= substr(md5($_SERVER['REMOTE_ADDR'] . "\t" . mt_rand() . "\t" . $_SERVER['HTTP_USER_AGENT']),-16);
		$sql_datas['regdate']	= $sql_datas['lastactivity'] = $sql_datas['lastvisit'] = $timestamp;
		$sql_datas['regip']		= $sql_datas['lastip'] = client_ip();

		if ($this->Config['extcredits_enable'])
		{
			$credits = ConfigHandler::get('credits');
			foreach ($credits['ext'] as $_k=>$_v)
			{
				if ($_v['enable'] && $_v['default'])
				{
					$sql_datas[$_k] = (int) $_v['default'];
				}
			}
		}

		$this->DatabaseHandler->Query("insert into ".TABLE_PREFIX."members (`".implode("`,`",array_keys($sql_datas))."`) values ('".implode("','",$sql_datas)."')");
		$uid = (int) $this->DatabaseHandler->Insert_ID();
		if($uid > 0)
		{
			$this->DatabaseHandler->Query("insert into ".TABLE_PREFIX."memberfields (`uid`,`nickname`) values ('$uid','{$sql_datas['nickname']}')");

			$qqwb_username = $this->Post['qqwb_username'];
			if($qqwb_username)
			{
				$this->DatabaseHandler->Query("insert into ".TABLE_PREFIX."qqwb_bind_info (`uid`,`qqwb_username`,`token`,`tsecret`,`dateline`,`synctoqq`) values ('$uid','$qqwb_username','{$this->Post['token']}','{$this->Post['tsecret']}','$timestamp',1)");
			}

			if($this->QQWBConfig['is_sync_face'] && $this->Post['synface'] && $this->Post['face'])
			{
				jsg_schedule(array('uid'=>$uid,'face'=>$this->Post['face']),'syn_qqwb_face');
			}

			if($this->Config['reg_email_verify'])
			{
				if(class_exists('Load')) Load::functions('my');

				if(function_exists('my_member_validate')) my_member_validate($uid,$sql_datas['email'],(int) $this->Config['normal_default_role_id']);
			}


			$this->_user_login($uid);

			$uc_syn_html = '';
			if(true===UCENTER && $ucuid > 0)
			{
				include_once(ROOT_PATH . 'uc_client/client.php');

				$uc_syn_html = uc_user_synlogin($ucuid);
			}
		}


		if($this->QQWBConfig['reg_pwd_display'])
		{
			$this->Messager("您的帐户 <strong>{$sql_datas['username']}</strong> 已经注册成功，请牢记您的密码 <strong>{$password}</strong>，现在为您转入到首页{$uc_syn_html}","?",10);
		}
		else
		{
			if($uc_syn_html)
			{
				$this->Messager("注册成功，现在为您转入到首页{$uc_syn_html}",'index.php');
			}
			else
			{
				$this->Messager(null,'index.php');
			}
		}
	}

	function LoginCheck()
	{
		exit($this->_login_check());
	}
	function _login_check()
	{
		$ip = client_ip();
		$timestamp = time();

		$in_ajax = $this->Request['in_ajax'];
		if($in_ajax)
		{
			$this->Post = array_iconv('utf-8',$this->Config['charset'],$this->Post);
		}

		$failed = $this->DatabaseHandler->FetchFirst("SELECT * FROM ".TABLE_PREFIX.'failedlogins'." WHERE ip='{$ip}'");
		if($failed)
		{
			if($failed['lastupdate'] + 900 > $timestamp)
			{
				if($failed['count'] > 5)
				{
					return '累计 5 次错误尝试，15 分钟内您将不能登录';
				}
			}
			else
			{
				$this->DatabaseHandler->Query("UPDATE ".TABLE_PREFIX.'failedlogins'." SET count='1', lastupdate='{$timestamp}' WHERE ip='{$ip}'");
				$this->DatabaseHandler->Query("DELETE FROM ".TABLE_PREFIX.'failedlogins'." WHERE lastupdate<{$timestamp}-901", 'UNBUFFERED');
			}
		}

		$return = '';

		$username = trim($this->Post['username']);
		$password = trim($this->Post['password']);
		if(!$username || !$password)
		{
			$return = '用户名或密码不能为空';
		}

		if($username && $password)
		{
			$user_info = $this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."members where `username`='{$username}'");
			if(!$user_info)
			{
				$return = '用户名已经不存在了';
			}
			else
			{
				if($user_info['password']!=md5($password))
				{
					$return = '用户名或密码错误';
				}
				else
				{
					$this->UserInfo = $user_info;
				}
			}

			if($return)
			{
				if($failed)
				{
					$this->DatabaseHandler->Query("UPDATE ".TABLE_PREFIX.'failedlogins'." SET count=count+1, lastupdate='$timestamp' WHERE ip='$ip'");
				}
				else
				{
					$this->DatabaseHandler->Query("REPLACE INTO ".TABLE_PREFIX.'failedlogins'." (ip, count, lastupdate) VALUES ('$ip', '1', '$timestamp')");
				}
			}
		}


		return $return;
	}
	function DoLogin()
	{
		if(($check_result = $this->_login_check()))
		{
			$this->Messager($check_result,null);
		}

		$this->_user_login($this->UserInfo);


		if(true===UCENTER && $this->UserInfo['ucuid'] > 0)
		{
			include_once(ROOT_PATH . 'uc_client/client.php');

			$uc_syn_html = uc_user_synlogin($this->UserInfo['ucuid']);

			$this->Messager("登录成功，现在为您转入到首页{$uc_syn_html}","?",5);
		}


		$qqwb_username = $this->Post['qqwb_username'];
		if($qqwb_username)
		{
			$this->DatabaseHandler->Query("insert into ".TABLE_PREFIX."qqwb_bind_info (`uid`,`qqwb_username`,`token`,`tsecret`,`dateline`) values ('{$this->UserInfo['uid']}','$qqwb_username','{$this->Post['token']}','{$this->Post['tsecret']}','$timestamp')");
		}


		$this->Messager(null,'index.php');
	}

	function UnBind()
	{
		$uid = max(0, (int) MEMBER_ID);
		if($uid < 1)
		{
			$this->Messager("请先登录",null);
		}

		$this->DatabaseHandler->Query("delete from ".TABLE_PREFIX."qqwb_bind_info where `uid`='$uid'");
		
		//同步财经的用户信息
		include_once ROOT_PATH."/caijing/CaijingUtil.php";
		$util = new CaijingUtil();
		$util->unlockQwb();

		$this->Messager("已经成功解除绑定");
	}

	function DoModifyBindInfo()
	{
		$uid = max(0, (int) MEMBER_ID);
		if($uid < 1)
		{
			$this->Messager("请先登录",null);
		}

		$synctoqq = ($this->Request['synctoqq'] ? 1 : 0);

		$this->DatabaseHandler->Query("update ".TABLE_PREFIX."qqwb_bind_info set `synctoqq`='$synctoqq' where `uid`='$uid'");


		$this->Messager("设置成功");
	}

	function _init_qqwb()
	{
		if ($this->Config['qqwb_enable'] && qqwb_init($this->Config))
		{
			if(!session_id())
			{
				session_start();
			}

			$this->QQWBConfig = ConfigHandler::get('qqwb');
			 
			if(MEMBER_ID > 0)
			{
				$this->QQWBBindInfo = $this->DatabaseHandler->FetchFirst("select * from ".TABLE_PREFIX."qqwb_bind_info where `uid`='".MEMBER_ID."'");
			}

			require_once(ROOT_PATH . 'include/qqwb/oauth.php');
		}
		else
		{
			$this->Messager("整合QQ微博的功能未开启",null);
		}

		;
	}

	function _get_oauth_url()
	{
		$callback = $this->Config['site_url'] . "/index.php?mod=qqwb&code=auth_callback";

		require_once(ROOT_PATH . 'include/qqwb/qqoauth.php');

		$QQAuth = new QQOAuth($this->QQWBConfig['app_key'],$this->QQWBConfig['app_secret']);

		$keys = $QQAuth->getRequestToken($callback);

		$_SESSION['qqwb_oauth_token_secret'] = $keys['oauth_token_secret'];
		jsg_setcookie('qqwb_oauth_token_secret',$_SESSION['qqwb_oauth_token_secret']);

		$aurl = $QQAuth->getAuthorizeURL($keys['oauth_token'], $callback);

		return $aurl;
	}

	function _user_login($uid)
	{
		if(is_array($uid))
		{
			$member = $uid;
		}
		else
		{
			$uid = max(0, (int) $uid);
			if($uid < 1)
			{
				return false;
			}
			$member = $this->DatabaseHandler->FetchFirst("SELECT `uid`,`username`,`password`,`secques`,`ucuid` FROM ".TABLE_PREFIX."members WHERE uid='$uid'");
		}

		if(!$member)
		{
			return false;
		}


		jsg_setcookie('sid', '', -86400000);
		jsg_setcookie('auth',authcode("{$member['password']}\t{$member['uid']}",'ENCODE'),(365*86400));


		return $member;
	}
}


?>
